package api

import (
	"openapi.itspire.cn/common/dict"
	"openapi.itspire.cn/common/global"
	"openapi.itspire.cn/common/throw"
	"openapi.itspire.cn/database"
	"openapi.itspire.cn/model"
	"openapi.itspire.cn/utils"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func LinkList(c *gin.Context) {
	var link model.Link

	list := make([]model.Link, 0)
	queryComment := database.Ins.
		Table(link.GetTableName()).
		Select("id,link_name,link_url").
		Where("delete_time = ? AND status = ?", dict.DeleteNot, dict.StatusOn).
		Order("id asc").
		Limit(global.LinkMax)
	if err := queryComment.Scan(&list).Error; err != nil {
		panic(err)
	}

	utils.Success(c, list)
}

func LinkApplyStatus(c *gin.Context) {
	var link model.Link

	userInfo := utils.GetUserInfo(c)
	id, _ := strconv.Atoi(utils.TypeAssertion(userInfo["id"]))
	if id == 0 {
		throw.AuthException(c, "账号尚未激活")
		return
	}

	status := -1
	res := database.Ins.Where("user_id = ?", id).First(&link)
	if res.RecordNotFound() == false {
		status = int(link.Status)
		if link.DeleteTime > dict.DeleteNot || (status == 0 && link.AuditTime > dict.StatusOff) {
			status = -2  // 删除/禁用
		}
	}

	maps := make(map[string]interface{})
	maps["status"] = status

	utils.Success(c, maps)
}

func LinkApplyList(c *gin.Context) {
	var link model.Link

	total := 0
	query := database.Ins.
		Model(&link).
		Where("delete_time = ?", dict.DeleteNot).
		Count(&total)
	if err := query.Count(&total).Error; err != nil {
		throw.ServerError(c, err.Error())
		return
	}

	list := make([]model.Link, 0)
	if total > 0 {
		queryComment := database.Ins.
			Table(link.GetTableName() + " a").
			Select("a.id,a.link_name,a.link_url,a.user_id,a.remarks,a.create_time,a.status,b.nickname").
			Joins("left join "+model.User{}.GetTableName()+" b on a.user_id = b.id").
			Where("a.delete_time = ?", dict.DeleteNot).
			Order("a.create_time desc")
		if err := queryComment.Scan(&list).Error; err != nil {
			panic(err)
		}
	}

	maps := make(map[string]interface{})
	maps["count"] = total
	maps["list"] = list

	utils.Success(c, maps)
}

func LinkCreate(c *gin.Context) {
	var link model.Link

	userInfo := utils.GetUserInfo(c)
	id, _ := strconv.Atoi(utils.TypeAssertion(userInfo["id"]))
	if id == 0 {
		throw.AuthException(c, "账号尚未激活")
		return
	}

	if err := c.ShouldBindJSON(&link); err != nil {
		throw.ParameterError(c, err.Error())
		return
	}

	timestamp := uint64(time.Now().Unix())

	res := database.Ins.Where("link_url = ?", link.LinkUrl).First(&link)
	if res.RecordNotFound() == false {
		throw.LogicException(c, "已申请，请勿重复申请", -1)
		return
	}

	total := 0
	query := database.Ins.
		Model(&link).
		Where("status = ? AND delete_time = ?", dict.StatusOn, dict.DeleteNot).
		Count(&total)
	if err := query.Count(&total).Error; err != nil {
		panic(err)
	}

	if total > global.LinkMax {
		throw.LogicException(c, "友链数量已达上限", -1)
		return
	}

	link.Status = 0
	link.UserId = uint64(id)
	link.CreateTime = timestamp
	res3 := database.Ins.NewRecord(link)
	if res3 {
		if err := database.Ins.Create(&link).Error; err != nil {
			panic(err)
		}
	}

	utils.Success(c, nil)
}
